package com.niuwa.p2p.service.impl.sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.dao.sequence.SequenceDao;
import com.niuwa.p2p.entity.Sequence;
import com.niuwa.p2p.service.sequence.ISequenceService;

@Service
public class SequenceServiceImpl implements ISequenceService {

	@Autowired
	private SequenceDao seqDao;
	@Override
	public long getNextSequenceBySeqKey(String seqKey) throws Exception {
		long seqValue =seqDao.getSeqValueBysSeqKey(seqKey);
		++seqValue;
		Sequence seq = new Sequence();
		seq.setSeqKey(seqKey);
		seq.setSeqValue(seqValue);
		seqDao.updateSequence(seq);
		return seqValue;
	}
	
	@Override
	public String getCompleteSequenceBySeqKey(String seqKey) throws Exception {
		String currentSeq =String.valueOf(getNextSequenceBySeqKey(seqKey));
		StringBuffer result=new StringBuffer(seqKey);
		int endpoint=6;//端点长度6
		int seqLength=currentSeq.length();//序列原始长度
		int shredLength=endpoint-seqLength;
		//判断自增序列长度，补全“0”
		for (int i = 0; i < shredLength; i++) {
			result.append("0");
		}
		result.append(currentSeq);
		return result.toString();
	}
	
	/**
	 * 生成编码好HH00001
	 * @param seqKey  HH
	 * @param numberLength 5
	 * @return
	 * @throws Exception
	 */
	public String getCompleteSequenceBySeqKey(String seqKey,int numberLength) throws Exception{
		String currentSeq =String.valueOf(getNextSequenceBySeqKey(seqKey));
		StringBuffer result=new StringBuffer(seqKey);
		int seqLength=currentSeq.length();//序列原始长度
		int shredLength=numberLength-seqLength;
		//判断自增序列长度，补全“0”
		for (int i = 0; i < shredLength; i++) {
			result.append("0");
		}
		result.append(currentSeq);
		return result.toString();
	}
}
